<?php

class DbCategory extends DbModel{
	public $table_name = "categories";

	private function _getParents(&$category){
		$ret = array();
		$category["parent"]= $this->row(array(
			"conditions" => array("id" => $category["parent_id"])
		));
		if($category["parent"] && $category["parent"]["parent_id"]){
			$this->_getParents($category["parent"]);
		}
	}

	public function get($id){
		$category = $this->row(array(
			"conditions" => array("id"=>$id)
		));
		if($category && $category["parent_id"]){
			$this->_getParents($category);
		}

		return $category;
	}
	
	public function search($keyword=false, $sortby="name", $sortorder="asc", $parent=false){
		$ret = $this->find(array(
			"conditions" => array(
				"parent_id" => $parent===false ? "0" : $parent
			),
			"order" => "$sortby $sortdir",
			"offset" => $page
		));
		
		if($ret && !empty($ret)){
			foreach($ret as &$row){
				$this->_getParents($row);
			}
		}
		
		return $ret;
	}
	
	public function tree(&$parent=null){
		if($parent){
			$parent["children"] = $this->find(array(
				"conditions" => array(
					"parent_id" => $parent["id"]
				),
				"order" => "position"
			));
			foreach($parent["children"] as &$child){
				$this->tree($child);
			}
		}else{
			$ret = $this->find(array(
				"conditions" => array(
					"parent_id" => 0
				),
				"order" => "position"
			));
			foreach($ret as &$item){
				$this->tree($item);
			}
		}
		return $ret;
	}
	private function _tree($id){
		if($id){
			if($item = $this->row(array("conditions"=>array("id"=>$id)))){
				$ret = $item;
				$ret["children"] = $this->_tree($id);
			}
		}
		return $ret;
	}
}

?>